package com.shiliao.app.activity.index.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.shiliao.app.R;
import com.shiliao.app.activity.index.entity.AddRemindEntity;
import com.shiliao.app.activity.index.presenter.NewsDetailPresenter;
import com.shiliao.app.activity.index.service.IAddRemindService;
import com.shiliao.app.activity.index.service.impl.AddRemindImpl;
import com.shiliao.app.activity.index.view.NewsDetailView;
import com.shiliao.app.activity.interlocution.dialog.QuestionDialog;
import com.shiliao.app.manager.YMUserManager;
import com.shiliao.app.splash.WelcomeActivity;
import com.shiliao.app.utils.FileNameManage;
import com.shiliao.app.utils.WebSetUtil;
import com.shiliao.app.utils.YMServerUtil;
import com.shiliao.app.weight.DragTV;
import com.shiliao.app.weight.ProgressWebView;
import com.umeng.socialize.UMShareAPI;
import com.yimei.framework.base.ui.BaseActivity;
import com.yimei.framework.network.ICallBack;
import com.yimei.framework.util.DensityUtils;
import com.yimei.framework.util.LogUtil;
import com.yimei.framework.util.ParseHelper;
import com.yimei.framework.util.PreferenceHelper;
import com.yimei.framework.util.StatusBarCompat;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * Created by yinzhiqiang on 2017/10/9.
 */

public class NewsDetailActivity extends BaseActivity implements NewsDetailView, View.OnClickListener, DragTV.floatClick {

    @BindView(R.id.actionbar_back)
    ImageView back;

    @BindView(R.id.action_title)
    TextView actionTitle;

    @BindView(R.id.action_prompt)
    ImageView actionPrompt;

    @BindView(R.id.webview)
    ProgressWebView webview;

    @BindView(R.id.index_comment)
    TextView comment; //输入评论的内容

    @BindView(R.id.iv_collection)
    ImageView mCollection;

    @BindView(R.id.iv_share)
    ImageView mShare;

//    @BindView(R.id.tv_release_comment)
//    TextView releaseComment;

    @BindView(R.id.float_image)
    DragTV floatImage;

    @BindView(R.id.tv_bg)
    TextView tvBg;

//    @BindView(R.id.view_loading)
//    ProgressBar loading;

    private String article_id;//评论的id
    private String userId;
    private String url;
    private String isCollection;//是否收藏
    private String isdianzan;//是否点赞
    private Boolean showCollection = false;//判断收藏和取消收藏
    private NewsDetailPresenter newsDetailPresenter;
    private MyWebView mWebView;
    private PopupWindow popMenu;
    private PopupWindow pomenuGuid;
    private View contentView;
    private ImageView remindGuide;
    private ImageView remindGuide1;
    private ImageView useful;
    private ImageView useless;
    private IAddRemindService addRemindService;
    private List<AddRemindEntity> remindList;
    private String shareTitle;//分享的title
    private String sharePicUrl;//分享的图标
    private String shareArticleUrl;//分享的链接
    private String shareDescription;//分享的描述
    private boolean isShow = false;
    private String isShowShare;
    private String isShowRemind;
    private QuestionDialog questionDialog;
    @Override
    public int getLayoutId() {
        return R.layout.activity_nesdetail;
    }

    @Override
    public void initView() {
        super.initView();
        WebSetUtil.setWebView(webview);
        newsDetailPresenter = new NewsDetailPresenter(this);
        userId = YMUserManager.getUserId(NewsDetailActivity.this);//获取userId
        Intent intent = getIntent();
        url = intent.getStringExtra("url");
        webview.loadUrl(url);
        if (url.contains("article.php?id")) {
            article_id = url.substring(url.indexOf("?id=") + 4);
            if (article_id.contains("&"))
                article_id = article_id.substring(0, article_id.indexOf("&"));

        }
        questionDialog=new QuestionDialog(this);
        newsDetailPresenter.requestShare(article_id, userId);
        newsDetailPresenter.requestIsCollection(article_id, userId);
        back.setOnClickListener(this);
//        releaseComment.setOnClickListener(this);
        mCollection.setOnClickListener(this);
        mShare.setOnClickListener(this);
        actionPrompt.setOnClickListener(this);
        actionPrompt.setVisibility(View.INVISIBLE);
        showLoadingView();
        mWebView = new MyWebView(webview);
        webview.setWebViewClient(mWebView);
        floatImage.setClickLister(this);
        comment.setOnClickListener(this);
        popuwind();

        //added by luyi to check if the article has reminder
        CheckRemind(article_id);
//        menuShow(relativeLayout);
        pipuwindow();
    }

    //added by luyi
    private void CheckRemind(String article_id) {
        Map map = new HashMap();
        if (!TextUtils.isEmpty(article_id)) {
            map.put("article_id", article_id);
        }
        addRemindService = new AddRemindImpl();
        addRemindService.requestRemind(YMServerUtil.ACTION_REMIND, map, new ICallBack() {
            @Override
            public void onSuccess(int statusCode, Object result) {
                remindList = ParseHelper.getModelList(result.toString(), "reminder_array", AddRemindEntity.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (!TextUtils.isEmpty(isShowRemind) && isShowRemind.equals("yes")) {//isShowRemind 为yes才显示引导
                            if (remindList != null && remindList.size() > 0) {
                                remindGuide.setVisibility(View.VISIBLE);
                                remindGuide1.setVisibility(View.VISIBLE);
                                PreferenceHelper.write(NewsDetailActivity.this, FileNameManage.WELCOME_PAGE,
                                        FileNameManage.WELCOME_PAGE_IDAILYREMIND_GUID, "no");//存储提醒指导
                            } else {
                                remindGuide.setVisibility(View.GONE);
                                remindGuide1.setVisibility(View.GONE);
                            }
                        } else {
                            remindGuide.setVisibility(View.GONE);
                            remindGuide1.setVisibility(View.GONE);
                        }
                    }
                });

                if (!remindList.isEmpty()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            actionPrompt.setVisibility(View.VISIBLE);
                        }
                    });
                }
            }

            @Override
            public void onFail(int statusCode, Object result) {

            }
        });
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus && !isShow) {
            isShow = true;
            if (!TextUtils.isEmpty(isShowShare) && isShowShare.equals("yes")
                    || !TextUtils.isEmpty(isShowRemind) && isShowRemind.equals("yes")) {
                if (StatusBarCompat.hasNavBar(this)){
                    int height= StatusBarCompat.getNavigationBarHeight(this);
                    if (Build.VERSION.SDK_INT>=26){
                        pomenuGuid.showAsDropDown(tvBg, 0, DensityUtils.px2dip(this,-height)+35);
                    }else{
                        pomenuGuid.showAsDropDown(tvBg, 0, DensityUtils.px2dip(this,-height)-20);
                    }
                }else{
                    pomenuGuid.showAsDropDown(tvBg, 0, 0);
                }
            }
        }
    }

    public void popuwind() {
        contentView = View.inflate(this, R.layout.popuwind_evaluate,
                null);
        popMenu = new PopupWindow(contentView,
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        popMenu.setBackgroundDrawable(new BitmapDrawable());
        popMenu.setFocusable(true);
        popMenu.setOutsideTouchable(true);
        useful = (ImageView) contentView.findViewById(R.id.iv_useful);
        useless = (ImageView) contentView.findViewById(R.id.iv_useless);
        useful.setOnClickListener(this);
        useless.setOnClickListener(this);
    }

    @Override
    public void onClick(final View v) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                switch (v.getId()) {
                    case R.id.actionbar_back://返回
                        finish();
                        break;
//                    case R.id.tv_release_comment://评论
//                        String commentContent = comment.getText().toString().trim();
//                        if (TextUtils.isEmpty(commentContent)) {
//                            showToast("请输入评论内容");
//                            return;
//                        }
//                        newsDetailPresenter.requestComment(article_id, userId, commentContent);
//                        break;
                    case R.id.iv_collection://收藏
                        clickCollection();
                        break;
                    case R.id.iv_share://分享
//                        newsDetailPresenter.requestShare(article_id,userId);
                        if (!TextUtils.isEmpty(shareArticleUrl)) {
                            InviteFriendDialog dialog = new InviteFriendDialog(NewsDetailActivity.this,
                                    shareArticleUrl, shareTitle, sharePicUrl, shareDescription, userId,
                                    "article", article_id);
                            dialog.show();
                        }
                        break;
                    case R.id.action_prompt://提醒
                        Intent intent = new Intent(NewsDetailActivity.this, AddRemindActivity.class);
                        intent.putExtra("article_id", article_id);
                        startActivity(intent);
                        break;
                    case R.id.iv_useful:
//                        showToast("有用");
                        newsDetailPresenter.requestEvaluate(article_id, userId, "1");
                        useful.setImageResource(R.mipmap.icon_like);
                        useless.setImageResource(R.mipmap.icon_evaluate_useless);
                        break;
                    case R.id.iv_useless:
//                        showToast("没用");
                        newsDetailPresenter.requestEvaluate(article_id, userId, "0");
                        useless.setImageResource(R.mipmap.icon_dislike);
                        useful.setImageResource(R.mipmap.icon_evaluate_useful);
                        break;
                    case R.id.index_comment:
                        questionDialog.setHintText("评论");
                        questionDialog.setTitleText("请输入评论内容");
                        questionDialog.show(false);
                        questionDialog.showKeyBoard();
                        questionDialog.setComfirn(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (TextUtils.isEmpty(questionDialog.getContent())) {
                                    showToast("请输入评论内容");
                                    return;
                                }
                                newsDetailPresenter.requestComment(article_id, userId, questionDialog.getContent());
                                questionDialog.dismiss();
                            }
                        });

                    default:
                        break;
                }
            }
        });

    }

    //点击收藏的处理
    public void clickCollection() {
        if (!TextUtils.isEmpty(isCollection) && isCollection.equals("no")) {
            if (!showCollection) {
                showCollection = !showCollection;
                newsDetailPresenter.requestCollection(article_id, userId);
            } else {
                showCollection = !showCollection;
                newsDetailPresenter.requestCancelArticle(article_id, userId);
            }
        } else {
            if (showCollection) {
                showCollection = !showCollection;
                newsDetailPresenter.requestCollection(article_id, userId);
            } else {
                showCollection = !showCollection;
                newsDetailPresenter.requestCancelArticle(article_id, userId);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void setCollectionIcon() {//收藏文章的图片
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mCollection.setImageResource(R.mipmap.icon_collection_sel);
            }
        });
    }

    @Override
    public void setNoCollection() {//没有收藏文章的图片
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mCollection.setImageResource(R.mipmap.icon_collection);
            }
        });
    }

    @Override
    public void loadPage() {//刷新页面
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                webview.loadUrl(url);
            }
        });
    }

    @Override
    public void commentSuccess() {//评论成功隐藏键盘,清掉内容
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showToast("评论成功");
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(comment.getWindowToken(), 0);
            }
        });
    }

    //分享的内容
    @Override
    public void shareContent(final String title, final String picUrl, final String articleUrl, final String description) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {//获取分享的内容(链接图片,描述)
//                InviteFriendDialog dialog=new InviteFriendDialog(NewsDetailActivity.this,
//                        articleUrl,title,picUrl,description);
//                dialog.show();
                shareTitle = title;
                shareArticleUrl = articleUrl;
                shareDescription = description;
                sharePicUrl = picUrl;
            }
        });

    }

    @Override
    public void isCollection(final String isShow, final String isScored) {//是否 收藏该文章,是否点赞
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                isCollection = isShow;
                isdianzan = isScored;
                LogUtil.e("yzq", isShow);
                if (!TextUtils.isEmpty(isShow) && isShow.equals("yes")) {
                    mCollection.setImageResource(R.mipmap.icon_collection_sel);
                }
                if (!TextUtils.isEmpty(isScored) && isScored.equals("1")) {
                    useful.setImageResource(R.mipmap.icon_like);
                    useless.setImageResource(R.mipmap.icon_evaluate_useless);
                } else if (!TextUtils.isEmpty(isScored) && isScored.equals("0")) {
                    useless.setImageResource(R.mipmap.icon_dislike);
                    useful.setImageResource(R.mipmap.icon_evaluate_useful);
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        UMShareAPI.get(this).release();
        pomenuGuid.dismiss();
        popMenu.dismiss();
    }

    @Override
    public void Click() {//点赞弹窗
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                popMenu.showAsDropDown(floatImage, 0, 5);
                //  popMenu.showAtLocation(floatImage, Gravity.LEFT| Gravity.START,0,0);

            }
        });
    }

    class MyWebView extends WebViewClient {
        public MyWebView(WebView webView) {

        }

        @Override
        public void onPageFinished(WebView view, String url) {//页面加载完成,取消loading
            super.onPageFinished(view, url);
            hideLoadingView();
        }
    }

    private void pipuwindow() {
        isShowShare = PreferenceHelper.readString(this, FileNameManage.WELCOME_PAGE,
                FileNameManage.WELCOME_PAGE_SHARE_GUID);//存储分享指导

        isShowRemind = PreferenceHelper.readString(this, FileNameManage.WELCOME_PAGE,
                FileNameManage.WELCOME_PAGE_IDAILYREMIND_GUID);//存储提醒指导

        View contentView = LayoutInflater.from(this).inflate(R.layout.layout_article_guide, null, false);
        pomenuGuid = new PopupWindow(contentView,
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        pomenuGuid.setBackgroundDrawable(new BitmapDrawable());
        pomenuGuid.setFocusable(true);
        pomenuGuid.setOutsideTouchable(true);
        remindGuide = contentView.findViewById(R.id.iv_remind_guid);
        remindGuide1 = contentView.findViewById(R.id.iv_remind_guid1);
        ImageView shareGuide = contentView.findViewById(R.id.iv_share_guide);
        ImageView shareGuide1 = contentView.findViewById(R.id.iv_share_guide1);
        RelativeLayout rlBg = contentView.findViewById(R.id.popwin_supplier_list_bottom);
        if (!TextUtils.isEmpty(isShowShare) && isShowShare.equals("yes")) {//isShowShare 为yes才显示引导
            shareGuide.setVisibility(View.VISIBLE);
            shareGuide1.setVisibility(View.VISIBLE);
            PreferenceHelper.write(NewsDetailActivity.this, FileNameManage.WELCOME_PAGE,
                    FileNameManage.WELCOME_PAGE_SHARE_GUID, "no");//存储提醒指导
        } else {
            shareGuide.setVisibility(View.GONE);
            shareGuide1.setVisibility(View.GONE);
        }

        rlBg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pomenuGuid.dismiss();
            }
        });

//        Handler handler=new Handler();
//        handler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                pomenuGuid.showAsDropDown(tvBg);
//            }
//        },500);
    }


}
